package com.framework.modules.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.common.config.SystemConfigName;
import com.framework.common.model.config.ConfigPaymentRateMoney2Coin;
import com.framework.common.utils.*;

import com.framework.modules.base.dao.UserIncomeHistoryDao;
import com.framework.modules.base.entity.UserBalanceEntity;
import com.framework.modules.base.entity.UserIncomeHistoryEntity;
import com.framework.modules.base.entity.UserPaymentEntity;
import com.framework.modules.base.service.UserBalanceService;
import com.framework.modules.base.service.UserIncomeHistoryService;
import com.framework.modules.base.service.UserPaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("userIncomeHistoryService")
public class UserIncomeHistoryServiceImpl extends ServiceImpl<UserIncomeHistoryDao, UserIncomeHistoryEntity> implements UserIncomeHistoryService {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private UserPaymentService userPaymentService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        EntityWrapper wrapper=new EntityWrapper<UserIncomeHistoryEntity>();
        if(params.containsKey("uid")){
            wrapper.eq("uid",params.get("uid"));
        }
        Page<UserIncomeHistoryEntity> page = this.selectPage(
                new Query<UserIncomeHistoryEntity>(params).getPage(),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryLiveIncomeHistory(Map<String, Object> params) {
        Page page=new Page(Integer.parseInt(params.get("page").toString()),Integer.parseInt(params.get("limit").toString()));
        return new PageUtils(page.setRecords(this.baseMapper.queryLiveIncomeHistory(page,params)));
    }

    @Override
    public Map<String,UserIncomeHistoryEntity> getMyIncome(Integer uid) {
        return this.baseMapper.getMyIncomeMap(uid);
    }

    @Transactional(isolation = Isolation.DEFAULT)
    @Override
    public Object updateIncome2balance(String type, Long uid) {
        /**
         * SELECT type,sum(income_money) as total_income
         * from tb_user_income_history
         * where state=0 and uid=8
         * group by type
         */
        //1.查询用户是否有未结算的收入
        List<UserIncomeHistoryEntity> incomes=this.baseMapper.getMyIncome(uid.intValue(),type);
        if(incomes.size()<1){
            return "你还无此收入";
        }
        BigDecimal incomeMoney=incomes.get(0).getIncomeMoney();
        //2.更新当前未结算的收入状态为 已结算 , update 语句
        this.baseMapper.updateMyIncomeState(uid.intValue(),type,1);
        logger.info(String.format("用户:%s,转入%s余额：%s",uid,type,incomeMoney));
        //更新余额
        Object object=userBalanceService.updateBalance(uid.intValue(), incomeMoney, "add");
        if(object instanceof String){
            return object.toString();
        }
        //3.写入账单 ， insert 语句
        UserPaymentEntity userPaymentEntity=new UserPaymentEntity();
        userPaymentEntity.setUid(uid.toString());
        userPaymentEntity.setType("income2balance");
        userPaymentEntity.setState("1");
        userPaymentEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
        userPaymentEntity.setOccurValue(incomeMoney);
        userPaymentEntity.setPostValue((BigDecimal)object);
        userPaymentEntity.setRemark("提现到余额");
        userPaymentService.insert(userPaymentEntity);
        return incomeMoney;
    }

    @Override
    public Object updateBlance2coin(Integer amount,Long uid) {
        UserBalanceEntity userBalanceEntity=userBalanceService.selectById(uid);
        BigDecimal balance=userBalanceEntity.getBalance();
        BigDecimal amou=new BigDecimal(amount);
        if(balance.compareTo(amou)==-1){
            return "余额不足";
        }
        //1。减余额
        Object object=userBalanceService.updateBalance(uid.intValue(),amou,"reduce");
        if(object instanceof String){
            return object.toString();
        }
        ConfigPaymentRateMoney2Coin configPaymentRateMoney2Coin=QuickHelper.getConfigValue(SystemConfigName.PAY_RATE_MONEY2COIN,ConfigPaymentRateMoney2Coin.class);
        Integer rate=configPaymentRateMoney2Coin.getGlobalRate();
        //2.加金币
        userBalanceService.addCoin(uid.intValue(),amount.intValue()*rate);
        //3.写入账单 ， insert 语句
        UserPaymentEntity userPaymentEntity=new UserPaymentEntity();
        userPaymentEntity.setUid(uid.toString());
        userPaymentEntity.setType("balance4coin");
        userPaymentEntity.setState("1");
        userPaymentEntity.setAdddate(DateUtils.getSecondTimestamp(new Date()));
        userPaymentEntity.setOccurValue(amou);
        userPaymentEntity.setPostValue((BigDecimal)object);
        userPaymentEntity.setRemark("余额转金币");
        return userPaymentService.insert(userPaymentEntity);
    }

}
